<?php
class OrderAction extends CommonAction
{
    function index(){
        $this->listmap = 1;
        $this->listmap .= " and o.site_id=" . $this->siteid;
        if ($this->_get('keywords')) {
            $this->listmap .= " and (yourname like '%".$this->_get('keywords')."%' or ordernumber like '%" . $this->_get('keywords') . "%' or member_id = '".$this->_get('keywords')."')";
            $this->keywords = $this->_get('keywords');
        }
        if ($this->_get('status', 'int') || $this->_get('status') == '0') {
            $this->listmap .= " and (o.status = " . $this->_get('status', 'int') . ")";
            $this->status = $this->_get('status');
        }
        if ($this->_get('stime')) {
            $this->listmap .= " and (create_time >= " . strtotime($this->_get('stime')) . ")";
            $this->stime = $this->_get('stime');
        }
        if ($this->_get('etime')) {
            $this->listmap .= " and (create_time <= " . (24 * 3600 + 1 * strtotime($this->_get('etime'))) . ")";
            $this->etime = $this->_get('etime');
        }

        $roleid=D('Role_user')->where('user_id = '.session(C('USER_AUTH_KEY')))->getfield('role_id');
        if($roleid==11||$roleid==12||$roleid==13) {
        }elseif(!session(C('ADMIN_AUTH_KEY'))){
            $this->myrole=1;
            $this->dao=D('Order_supplier');
            $myid=D('User')->where(' id = '.session(C('USER_AUTH_KEY')))->getField('member_id');
            $mysupplier_id=D('Supplier')->where('member_id = '.$myid)->getfield('id');
            $this->listmap .= ' and supplier_id = '.$mysupplier_id;
        }
        parent::_list("o", "left join __MEMBER__ as m on m.id=o.member_id", "o.*,m.nickname,m.username");
        $list = $this->get('list');
        $saleDB = M('sale');
        foreach ($list as $key => $value) {
            $data = $saleDB->where(array('order_id' => $value['id']))->group("status")->select();
            $list[$key]['coupon_total'] = M('Coupon_sn') -> alias('cs') -> join('__COUPON__ as c on c.id = cs.coupon_id') ->where(array('sn' => $value['coupon_sn_id']))->getField('c.discount');
            $list[$key]['paytypename']  =  M('Payment') -> where(array('id' => $value['payment_id'])) -> getField('title');
            $num = count($data);
            if ($num > 1) {
            } elseif ($num == 1 && $data['0']['status'] == 1) {
            }
            if(!session(C('ADMIN_AUTH_KEY'))&&$roleid!=11&&$roleid!=12&&$roleid!=13) {
                $list[$key]['id'] = $value['order_id'];
            }
        }
        $this->assign('list', $list);
        $this->display();
    }
    //后台付款
    function payment()
    {
        $order_id = $this->_post('order_id');
        $remark = $this->_post('remark');
        $orderDB = D('order');
        $memberDB = M('member');
        $member_account_logDB = M('member_account_log');
        $order = $orderDB->where(array('id' => $order_id))->find();
        $member = $memberDB->where(array('id' => $order['member_id']))->find();
        if ($order['status'] == 1) {
            $mes = $orderDB->upstate($order['ordernumber']);
            if ($mes) {
                $data['site_id'] = $this->siteid;
                $data['member_id'] = $order['member_id'];
                $data['order_id'] = $order['id'];
                $data['product_id'] = 0;
                $data['status'] = 0;
                $data['deep'] = 0;
                $data['num'] = 0;
                $data['changenum'] = $order['total'];
                $data['goodsMoney'] = $order['total'];
                $data['remark'] = '管理员代为付款：'.$remark;
                $data['pdstate'] = 0;
                $member_account_logDB->add($data);
                //通知用户后台已付款
                $domain = M('Site')->where(array('id' => $this->siteid))->getField('domain');
                if ($domain == '') {
                    $siteid = $this->siteid;
                } else {
                    $siteid = 0;
                }
                $msg = "您的订单: " . $order['ordernumber'] . " 已在后台付款,[管理员] \r\n<a href=\"" . U('Member/Order/read', array('id' => $order['id']), true, false, true, $siteid) . "\">点击查看</a>订单详情";
                sendWXMsg($member['openid'], $msg);
                $this->success('操作成功');
            } else {
                $this->error('付款失败');
            }
        } else {
            $this->error('此商品已经付款');
        }
    }
	
	
	
	public function changeSuppier(){
		$saleid = $this->_post('saleid');
		$supplierid = $this->_post('supplierid');
		$map['site_id'] = $this->siteid;
		$map['id'] = $saleid;
		$sdb = M('Sale');
		$ret = $sdb -> where($map) -> data(array('supplier_id' => $supplierid)) -> save();
		if($ret !== false){
			$this->success('操作成功');
		}else{
			$this->error('操作失败，'.$sdb -> getLastSql());
		}
	}
    function edit(){
        $roleid=D('Role_user')->where('user_id = '.session(C('USER_AUTH_KEY')))->getfield('role_id');
        if($roleid==11||$roleid==12||$roleid==13) {
            $this->list = $this->dao->getAllProduct($this->_get('id'));
        }elseif(!session(C('ADMIN_AUTH_KEY'))){
            $myid=D('User')->where(' id = '.session(C('USER_AUTH_KEY')))->getField('member_id');
            $mysupplier_id=D('Supplier')->where('member_id = '.$myid)->getfield('id');
            $this->list = $this->dao->getAllProduct($this->_get('id'),$mysupplier_id);
        }else{
            $this->list = $this->dao->getAllProduct($this->_get('id'));
        }
        $info = $this->dao->where(array('id' => $this->_get('id')))->find();
		$this->suppier = M('Supplier') -> where('site_id='.$this->siteid) -> select();
        $this->assign('info', $info);
        $this->display();
    }
    //更新物流
    function logistics()
    {
        $order_id = $this->_post('order_id');
        $logistics_num = $this->_post('logistics_num');
        //更新物流单号
        $orderDB = M('order');
        //判断是否支付
        $order = $orderDB->where(array('id' => $order_id))->find();
        if ($order['status'] == 3) {
            $this->error("订单已发货");
            exit;
        } elseif ($order['status'] != 2) {
            $this->error("订单尚未支付");
            exit;
        }
        $mes = $orderDB->where(array('id' => $order_id))->save(array('logistics_num' => $logistics_num, 'status' => 3));
        if ($mes) {
            $this->success("发货成功");
        } else {
            $this->error("更新订单失败");
        }
    }
    public function _list()
    {
        //计算总页数
        $count = $this->dao->alias('n')->join('left join __PRODUCT_CATEGORY__ c ON n.category_id= c.id')->Field('n.*,c.title as category_name')->where($this->listmap)->count();
        import('ORG.Util.Page');
        //实例化分页类
        $p = new Page($count, $this->pagesize);
        $this->list = $this->dao->alias('n')->join('left join __PRODUCT_CATEGORY__ c ON n.category_id= c.id')->Field('n.*,c.title as category_name, c.name as cate_name')->where($this->listmap)->order($this->listorder)->limit($p->firstRow . ',
' . $p->listRows)->select();
        $this->pages = $p->show();
    }
    public function add()
    {
        //供货商
        $this->SupplierList = M('Supplier')->where(array('site_id' => $this->siteid))->select();
        $this->cate_list = D('Product_category')->getListToArray1(0, $this->siteid);
        //固定栏目及字段扩展
        $SiteModel = M('Site');
        $curTemplate = $SiteModel->where('id=' . $this->siteid)->Field("productExtendsField as productExtendsField")->find();
        $this->extendsField = json_decode($curTemplate['productExtendsField'], true);
        parent::add();
    }
    //添加商品
    public function addProduct()
    {
        $this->dao = D('Product');
        $this->listmap = "1 and n.site_id=" . $this->siteid;
        $this->listorder = "sort,id";
        if (isset($_GET['category_id']) && intval($_GET['category_id']) > 0) {
            $this->listmap .= " and n.category_id=" . intval($_GET['category_id']);
            $this->category_id = intval($_GET['category_id']);
        }
        //搜索标题
        if (isset($_GET['keywords']) && $_GET['keywords'] != '') {
            $keywords = $_GET['keywords'];
            $_GET['keywords'] = urlencode($_GET['keywords']);
            $this->listmap .= " and n.title like '%{$keywords}%'";
            $this->keywords = $keywords;
        }
        $this->categoryList = M('Product_category')->where(array('site_id' => $this->siteid))->select();
        $this->_list();
        $this->display();
    }
    // ajax更新字段
    public function ajaxText()
    {
        $table = str_replace(C('DB_PREFIX'), '', $this->_post('tablename'));
        $field = $this->_post('field');
        $id = $this->_post('id');
        $val = $this->_post('val');
        $db = M($table);
        if ($table == 'nav') {
            if ($field == 'link') {
                if (!(substr($val, 0, 7) == 'http://' || substr($val, 0, 8) == 'https://' || substr($val, 0, 7) == 'mailto:' || substr($val, 0, 4) == 'tel:')) {
                    $val = "__APP__" . $val;
                }
            }
        }
        $ret = $db->where(array('id' => $id))->data(array($field => (float)$val, 'ordernumber' => build_order_no()))->save();
        if ($ret !== false) {
            $re['status'] = 1;
            $re['data'] = $val;
            $re['info'] = '更新成功';
        } else {
            $re['status'] = 0;
            $re['data'] = $val;
            $re['info'] = $db->getError();
        }
        echo json_encode($re);
    }
    //显示商品SKU
    public function product()
    {
        if ($this->_get('id')) {
            $id = intval($_GET['id']);
            //当前站点数据ID
            $map['site_id'] = $this->siteid;
            $map['id'] = $id;
            //扩展字段
            $productModel = D('Product');
            //规格和属性
            $skuList = $productModel->getSKUListById($id);
            $SKU = $productModel->getSKUById($id);
            //商品数据
            $info = $productModel->where(array('id' => $id))->find();
            $Product_categoryModel = D('Product_category');
            $typeid = $Product_categoryModel->getTypeById($info['category_id'], $this->siteid);//当前类型ID
            //通过typeid查询当前类型
            $template = M('Type')->where(array('id' => $typeid))->find();
            $info['goods_id'] = $id;
            $this->assign($info);
            $this->assign('skuList', $skuList);
            $this->assign('SKU', $SKU);
            $this->display();
        }
    }
    //订单退款处理
    public function refund()
    {
        $order_id = $this->_get('id');
        $status = $this->_post('status');
        if (IS_POST) {
            $orderDB = M('order');
            $order_id = $this->_post('id');
            $order = $orderDB->where(array('id' => $order_id))->find();
            if ($status == 0) {
                $mes = $orderDB->where(array('id' => $order_id))->save(array('status' => 2));
                if ($mes) {
                    //插入日志表
                    $data["remark"] = "审核失败";
                    $data["user_id"] = session(C('USER_AUTH_KEY'));
                    $data["order_id"] = $order_id;
                    $data["time"] = time();
                    $memberDb = M('Member');
                    $openid = $memberDb->where(array('id' => $order['member_id']))->getField('openid');
                    $text = "尊敬的用户:\r\n您的订单" . $order['ordernumber'] . "退款审核失败，请重新申请";
                    sendWXMsg($openid, $text);
                    //插入日志表
                    $data["remark"] = $text;
                    $data["user_id"] = session(C('USER_AUTH_KEY'));
                    $data["order_id"] = $order_id;
                    $data["time"] = time();
                    M('returngoods')->add($data);
                    $this->success('操作成功', U('index'));
                    exit;
                } else {
                    $this->success('操作失败', U('index'));
                    exit;
                }
            } elseif ($status == 1) {
                $mes = $orderDB->where(array('id' => $order_id))->save(array('status' => 0));
                if ($mes) {
                    //撤消分成
                    $Member_account_logdb = D('Member_account_log');
                    //$Member_account_logdb -> cancel($sale['order_id'], $sale['product_id'], $sale['attr']);
                    $Member_account_logdb->where(array('order_id' => $order_id, 'pdstate' => 3))->save(array('status' => 0));
                    //退货商品
                    $memberDb = M('Member');
                    $openid = $memberDb->where(array('id' => $order['member_id']))->getField('openid');
                    $memberDb->where(array('id' => $order['member_id']))->setInc('money', $order['total']);
                    $text = "尊敬的用户:\r\n您的账户资金增加" . abs($order['total']) . "\r\n原因: 订单" . $order['ordernumber'] . " 退款";
                    $moneydata['user_id'] = session(C('USER_AUTH_KEY'));
                    $moneydata['member_id'] = $order['member_id'];
                    $moneydata['remark'] = $text;
                    $moneydata['changenum'] = $order['total'];
                    $moneydata['dateline'] = time();
                    $Member_account_logdb->add($moneydata);
                    sendWXMsg($openid, $text);
                    //插入日志表
                    $data["remark"] = "退款完成";
                    $data["user_id"] = session(C('USER_AUTH_KEY'));
                    $data["order_id"] = $order_id;
                    $data["time"] = time();
                    M('returngoods')->add($data);
                    $this->success('操作成功', U('index'));
                    exit;
                } else {
                    $this->success('操作失败', U('index'));
                    exit;
                }
            }
        }
        $returngoodsDB = D('Returngoods');
        $data = $returngoodsDB->_list(array('order_id' => $order_id), '', 10);
        $this->assign('order_id', $order_id);
        $this->assign('list', $data['list']);
        $this->assign('pages', $data['pages']);
        $this->display();
    }
    public function confirm(){
        $order_id=$this->_get('id');
        $siteid=$this->siteid;
        $orderDB=D('order');
        $end=$orderDB->confirm($order_id,$siteid);
        if($end){
            $this->success('订单已确认',U('Order/index'));
        }else{
            $this->error('订单确认失败',U('Order/index'));
        }
    }
}